import uiautomator2 as u2
import time
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def connect_device():
    """
    连接设备
    Returns:
        u2.Device: 设备连接对象
    """
    try:
        logger.info("正在连接设备...")
        # 连接设备（会自动连接第一个可用设备）
        device = u2.connect()
        logger.info(f"设备连接成功: {device.info}")
        return device
    except Exception as e:
        logger.error(f"设备连接失败: {str(e)}")
        raise

def start_bilibili_app(device):
    """
    启动 B站应用
    Args:
        device: 设备连接对象
    """
    try:
        logger.info("正在启动 B站应用...")
        # 启动 B站应用
        device.app_start("tv.danmaku.bili")
        time.sleep(3)  # 等待应用启动
        logger.info("B站应用启动成功")
    except Exception as e:
        logger.error(f"启动 B站应用失败: {str(e)}")
        raise

def handle_teen_protection(device):
    """
    处理青少年保护弹窗
    Args:
        device: 设备连接对象
    """
    try:
        # 查找青少年保护弹窗
        if device(text="我知道了").exists(timeout=3):
            device(text="我知道了").click()
            logger.info("已处理青少年保护弹窗")
        elif device(resourceId="text3").exists(timeout=3):
            device(resourceId="text3").click()
            logger.info("已处理青少年保护弹窗")
        else:
            logger.info("未发现青少年保护弹窗")
    except Exception as e:
        logger.warning(f"处理青少年保护弹窗时出错: {str(e)}")

def debug_page_elements(device):
    """
    调试当前页面元素，帮助找到正确的ID
    Args:
        device: 设备连接对象
    """
    try:
        logger.info("正在分析当前页面元素...")
        
        # 获取当前页面所有可点击元素
        clickable_elements = device(clickable=True)
        if clickable_elements.exists():
            logger.info(f"找到 {clickable_elements.count} 个可点击元素")
            
            for i in range(min(clickable_elements.count, 10)):
                elem = clickable_elements[i]
                try:
                    info = elem.info
                    resource_id = info.get('resourceId', '')
                    text = info.get('text', '')
                    content_desc = info.get('contentDescription', '')
                    
                    if any(keyword in str(resource_id).lower() for keyword in ['search', 'expand']):
                        logger.info(f"可能的搜索元素: resourceId='{resource_id}', text='{text}', desc='{content_desc}'")
                except:
                    continue
        
        # 查找包含"搜索"文字的元素
        search_text_elements = device(textContains="搜索")
        if search_text_elements.exists():
            logger.info(f"找到包含'搜索'文字的元素: {search_text_elements.count} 个")
            for i in range(search_text_elements.count):
                try:
                    elem = search_text_elements[i]
                    info = elem.info
                    logger.info(f"搜索元素 {i+1}: resourceId='{info.get('resourceId', '')}', text='{info.get('text', '')}', bounds='{info.get('bounds', '')}'")
                except:
                    continue
        
        # 检查是否有放大镜图标
        magnify_elements = device(description="搜索")
        if magnify_elements.exists():
            logger.info("找到搜索图标元素")
            
    except Exception as e:
        logger.error(f"调试页面元素时出错: {str(e)}")

def search_videos(device, keyword):
    """
    搜索视频
    Args:
        device: 设备连接对象
        keyword: 搜索关键词
    """
    try:
        logger.info("开始搜索流程...")
        
        # 先调试页面元素
        debug_page_elements(device)
        
        # 尝试多种可能的搜索框定位方式
        search_selectors = [
            {"resourceId": "expand_search"},
            {"resourceId": "tv.danmaku.bili:id/expand_search"},
            {"textContains": "搜索"},
            {"description": "搜索"},
            {"className": "android.widget.ImageView", "clickable": True},
            {"className": "android.widget.TextView", "textContains": "搜索"}
        ]
        
        search_clicked = False
        for selector in search_selectors:
            try:
                if device(**selector).exists(timeout=2):
                    device(**selector).click()
                    logger.info(f"使用选择器 {selector} 成功点击搜索")
                    search_clicked = True
                    break
            except Exception as e:
                continue
        
        if not search_clicked:
            logger.error("尝试所有搜索框定位方式都失败了")
            return
            
        time.sleep(1)
        
        # 尝试多种输入框定位方式
        input_selectors = [
            {"resourceId": "search_src_text"},
            {"resourceId": "tv.danmaku.bili:id/search_src_text"},
            {"className": "android.widget.EditText"},
            {"focusable": True, "className": "android.widget.EditText"}
        ]
        
        input_found = False
        for selector in input_selectors:
            try:
                if device(**selector).exists(timeout=2):
                    device(**selector).set_text(keyword)
                    logger.info(f"使用选择器 {selector} 成功输入关键词: {keyword}")
                    input_found = True
                    break
            except Exception as e:
                continue
                
        if not input_found:
            logger.error("找不到搜索输入框")
            return
            
        # 按回车搜索
        device.press("enter")
        logger.info("已执行搜索")
        
        # 等待搜索结果加载
        time.sleep(3)
        
        # 获取搜索结果
        logger.info("正在获取搜索结果...")
        get_search_results(device)
            
    except Exception as e:
        logger.error(f"搜索过程中出错: {str(e)}")
        raise

def get_search_results(device):
    """
    获取搜索结果
    Args:
        device: 设备连接对象
    """
    # 尝试多种标题元素定位方式
    title_selectors = [
        {"resourceId": "title"},
        {"resourceId": "tv.danmaku.bili:id/title"},
        {"className": "android.widget.TextView", "clickable": True},
        {"className": "android.widget.TextView"}
    ]
    
    for selector in title_selectors:
        try:
            titles = device(**selector)
            if titles.exists():
                title_count = titles.count
                logger.info(f"使用选择器 {selector} 找到 {title_count} 个结果")
                
                # 遍历并打印所有标题
                results_found = False
                for i in range(min(title_count, 15)):  # 限制显示数量
                    try:
                        title_text = titles[i].get_text()
                        if title_text and len(title_text) > 3:  # 过滤太短的文本
                            print(f"{i+1}. {title_text}")
                            results_found = True
                    except Exception as e:
                        continue
                
                if results_found:
                    return
        except Exception as e:
            continue
    
    logger.warning("未找到任何有效的搜索结果")

def main():
    """
    主函数
    """
    device = None
    try:
        # 连接设备
        device = connect_device()
        
        # 启动 B站应用
        start_bilibili_app(device)
        
        # 处理青少年保护弹窗
        handle_teen_protection(device)
        
        # 搜索视频
        search_videos(device, "白月黑羽")
        
        input('\n**** 按回车键退出..')
        
    except Exception as e:
        logger.error(f"程序执行出错: {str(e)}")
    finally:
        if device:
            logger.info("程序执行完毕")

if __name__ == "__main__":
    main() 